package sms;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;


public class PortHandler 
{
	 private CommPortIdentifier portId;
	 private InputStream inputDataStream;
	 private OutputStream outputDataStream;
	 private SerialPort serialPort;
	 private String commport;
	 private String databits;
	 private String stopbits;
	 private String parity;
	 private String baudrate;
	
	public PortHandler(String commport, String baudrate)
	{
		this.baudrate = baudrate;
		this.commport = commport;
		 serialPort = null;
	     databits = "8";
	     stopbits = "1";
	     parity = "None";
	}
	public PortHandler() 
	{
		 serialPort = null;
	     commport = "COM4";
	     databits = "8";
	     stopbits = "1";
	     parity = "None";
	     baudrate = "115200";
	}
	
	@SuppressWarnings("unchecked")
	public boolean getComPort()
	{
	     Enumeration portList = CommPortIdentifier.getPortIdentifiers();
	     while(portList.hasMoreElements()) 
	     {
	         portId = (CommPortIdentifier)portList.nextElement();
	         if(portId.getName().equals(commport))
	         {
	             System.out.println(portId.getName());
	             initialize();
	             connect();
	             System.out.println((new StringBuilder()).append(portId.getName()).append(" is found .").toString());
	             return true;
	         }
	     }
	     return false;
	 }
	
	 public boolean initialize()
	 {
	     try
	     {
	         serialPort = (SerialPort)portId.open("GsmControl", 2000);
	         try
	         {
	             int x = 0;
	             int y = 0;
	             int z = 0;
	             if(Integer.parseInt(databits) == 7)
	                 x = 7;
	             else
	             if(Integer.parseInt(databits) == 8)
	                 x = 8;
	             if(Integer.parseInt(stopbits) == 1)
	                 y = 1;
	             else
	             if(stopbits.equalsIgnoreCase("1.5"))
	                 y = 3;
	             else
	             if(Integer.parseInt(stopbits) == 2)
	                 y = 2;
	             if(parity.equalsIgnoreCase("none"))
	                 z = 0;
	             else
	             if(parity.equalsIgnoreCase("even"))
	                 z = 2;
	             else
	             if(parity.equalsIgnoreCase("odd"))
	                 z = 1;
	             serialPort.setSerialPortParams(Integer.parseInt(baudrate), x, y, z);
	             serialPort.setFlowControlMode(0);
	         }
	         catch(Exception e)
	         {
	             e.printStackTrace();
	             serialPort.close();
	             return false;
	         }
	     }
	     catch(Exception e)
	     {
	    	 e.printStackTrace();
	         return false;
	     }
	     
	     try 
	     {
			inputDataStream = serialPort.getInputStream();
			outputDataStream = serialPort.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
	     return true;
	 }
	
	 public boolean connect()
	 {
	     String ans1;
	     try
	     {
	         String reply = sendAndRecvCommand(new String("AT\r"), 100);
	         System.out.println((new StringBuilder()).append("Reply : ").append(reply).toString());
	         if(reply.indexOf("OK") != -1)
	         {
	             System.out.println("Modem is Connected successfully..");
	         } else
	         {
	             serialPort.close();
	             inputDataStream.close();
	             outputDataStream.close();
	             return false;
	         }
	     }
	     catch(Exception e)
	     {
	         e.printStackTrace();
	         serialPort.close();
	         return false;
	     }
	     ans1 = sendAndRecvCommand(new String("AT+CMGF=1\r"), 100);
	     if(ans1.indexOf("OK") == -1);
	     return true;
	 }

	 public void disConnet()
	 {
	     try
	     {
	         System.out.println("Discconnecting....");
	         serialPort.close();
	         inputDataStream.close();
	         outputDataStream.close();
	     }
	     catch(Exception e)
	     {
	         e.printStackTrace();
	     }
	 }
	 
	public String sendAndRecvCommand(String s, int timeout)
	 {
	     String strIn;
	     try
	     {
	    	 inputDataStream.skip(inputDataStream.available());
	         s = (new StringBuilder()).append(s).append("\r").toString();
	         System.out.println((new StringBuilder()).append("Command to execute is : ").append(s).toString());
	         outputDataStream.write(s.getBytes());
	         outputDataStream.flush();
	         strIn = new String();
	         int i = 0;
	         do
	         {
	             if(i >= timeout)
	                 break;
	             int numChars = inputDataStream.available();
	             if(numChars > 0)
	             {
	                 byte bb[] = new byte[numChars];
	                 inputDataStream.read(bb, 0, numChars);
	                 strIn = (new StringBuilder()).append(strIn).append(new String(bb)).toString();
	             }
	             System.out.println((new StringBuilder()).append("Reply is : ").append(strIn).toString());
	             if(strIn.indexOf(">\r\n") != -1 || strIn.indexOf("OK\r\n") != -1 || strIn.indexOf("ERROR") != -1 && strIn.indexOf("\r\n", strIn.indexOf("ERROR") + 1) != -1)
	                 break;
	             Thread.sleep(100);
	             i++;
	         } while(true);
	         if(strIn.length() == 0)
	             return "ERROR: len 0";
	     }
	     catch(Exception e)
	     {
	         e.printStackTrace();
	         try
	         {
	             for(boolean tempFlag = false; !tempFlag; tempFlag = connect())
	             {
	                 Thread.sleep(5000L);
	                 disConnet();
	                 initialize();
	             }
	         }
	         catch(Exception ie)
	         {
	             e.printStackTrace();
	         }
	         return "ERROR: Sending or Receing Problem";
	     }
	     return strIn;
	 }
	

}
